package org.geoserver.jtilecache.tile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BBOX {

	private static Log log = LogFactory.getLog(org.geoserver.jtilecache.tile.BBOX.class);

	private static String DELIMITER = ",";

	private double minx;
	private double maxx;
	private double miny;
	private double maxy;

	public BBOX(String BBOX) {
		setFromBBOXString(BBOX);
		if(log.isTraceEnabled()) {
			log.trace("Created BBOX: " + getReadableString());
		}
	}

	public BBOX(String[] BBOX) {
		setFromStringArray(BBOX);
		if(log.isTraceEnabled()) {
			log.trace("Created BBOX: " + getReadableString());
		}
	}

	public BBOX(double minx, double miny, double maxx, double maxy) {
		setMinimumX(minx);
		setMinimumY(miny);
		setMaximumX(maxx);
		setMaximumY(maxy);
		if(log.isTraceEnabled()) {
			log.trace("Created BBOX: " + getReadableString());
		}
	}

	/**
	 * Sets from an array of strings
	 * @param BBOX
	 */
	public void setFromStringArray(String[] BBOX) {
		if(BBOX.length == 4) {
			setMinimumX(Double.valueOf(BBOX[0]).doubleValue());
			setMinimumY(Double.valueOf(BBOX[1]).doubleValue());
			setMaximumX(Double.valueOf(BBOX[2]).doubleValue());
			setMaximumY(Double.valueOf(BBOX[3]).doubleValue());
		} else if(BBOX.length == 1) {
			setFromBBOXString(BBOX[0]);
		}
	}

	/**
	 * Parses the BBOX parameters from a comma separted value list
	 * @param BBOX
	 */
	public void setFromBBOXString(String BBOX) {
		String[] tokens = BBOX.split(DELIMITER);
		setFromStringArray(tokens);
	}


	public void setMinimumX(double x) {
		this.minx = x;
	}

	public void setMinimumY(double y) {
		this.miny = y;
	}

	public void setMaximumX(double x) {
		this.maxx = x;
	}

	public void setMaximumY(double y) {
		this.maxy = y;
	}

	public double getMinimumX() {
		return this.minx;
	}

	public double getMinimumY() {
		return this.miny;
	}

	public double getMaximumX() {
		return this.maxx;
	}

	public double getMaximumY() {
		return this.maxy;
	}

	/**
	 * Outputs a string suitable for logging and other human-readable tasks
	 * @return a readable string
	 */
	public String getReadableString() {
		return "Min X: " + this.minx + " Min Y: " + this.miny +
			" Max X: " + this.maxx + " Max Y: " + this.miny;
	}

	/**
	 * Returns a comma separated value String suitable for URL output
	 */
	public String toString() {
		StringBuffer buff = new StringBuffer(40);
		buff.append(minx);
		buff.append(',');
		buff.append(miny);
		buff.append(',');
		buff.append(maxx);
		buff.append(',');
		buff.append(maxy);
		return buff.toString();
	}

	public boolean equals(BBOX other) {
		return this.maxx == other.maxx && this.minx == other.minx
				&& this.miny == other.miny && this.maxy == other.maxy;
	}
}
